(function() {
    const tb = document.querySelector('.tb')
    const form = document.querySelector('form')
    
    function render() {
        axios({
            method: 'GET',
            url: 'http://www.liulongbin.top:3006/api/getbooks'
        }).then(({data: {status, msg, data}}) => {
            // console.log(res);
            if(status !== 200) return alert(msg)
            const htmlStr = data.map(({id, author, bookname, publisher}) => `
            <tr>
                <th scope="row">${id}</th>
                <td>${bookname}</td>
                <td>${author}</td>
                <td>${publisher}</td>
                <td>
                  <button type="button" class="btn btn-link btn-sm" data-id="${id}">删除</button>
                </td>
            </tr>
            `).join('')
            tb.innerHTML = htmlStr
        })
    }
    render()

    tb.addEventListener('click' , function(e) {
        // console.log(e.target.dataset.id);
        if(e.target.tagName === 'BUTTON') {
            const id = e.target.dataset.id
            axios({
                method: 'delete',
                url: `http://www.liulongbin.top:3006/api/delbook?id=${id}`
            }).then(({ status, msg }) => {
                // console.log(res);
                if(status !== 200) return alert(msg)
                
                render()
            })
        }
        
    })


    form.addEventListener('submit' , function(e) {
        e.preventDefault()

        const bookname = document.querySelector('#iptBookname').value.trim()
        const author = document.querySelector('#iptAuthor').value.trim()
        const publisher = document.querySelector('#iptPublisher').value.trim()

        axios({
            method: 'POST',
            url: 'http://www.liulongbin.top:3006/api/addbook',
            data: {
                bookname,
                author,
                publisher
            }
        }).then(({ status , msg }) => {
            // console.log(res); 
            if(status !== 200) return alert(msg)
            render()

            form.reset()
        })
    })
})()